/**
 * @ClassName ProfitAnalysisServiceImpl
 * @Description TODO
 * @Author 沉默小吴
 * @Date 2024/12/17 14:55
 */
package com.tledu.operate.count.service.impl;

import com.tledu.operate.count.entity.ProfitAnalysis;
import com.tledu.operate.count.entity.vo.ProfitAnalysisJSON;
import com.tledu.operate.count.mapper.ProfitAnalysisRepository;
import com.tledu.operate.count.service.IProfitAnalysisService;
import com.tledu.operate.count.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ProfitAnalysisServiceImpl implements IProfitAnalysisService {
    @Autowired
    private ProfitAnalysisRepository profitAnalysisRepository;
    @Override
    public ProfitAnalysisJSON getProfitAnalysis(Long departmentId, String startDate, String endDate, String granularity) {
        List<ProfitAnalysis> profitAnalyses = profitAnalysisRepository.getProfitAnalysis(departmentId, startDate, endDate);
        ProfitAnalysisJSON profitAnalysisJSONS = new ProfitAnalysisJSON();
        List<String> dataAxis = new ArrayList<>();
        List<BigDecimal> data = new ArrayList<>();

        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");

        for (ProfitAnalysis profitAnalyse : profitAnalyses) {
            try {
                Date date = inputFormat.parse(profitAnalyse.getRecordTime());
                String formattedDate = outputFormat.format(date);
                dataAxis.add(formattedDate);
            } catch (Exception e) {
                e.printStackTrace();
                dataAxis.add(profitAnalyse.getRecordTime()); // Fallback to original value if parsing fails
            }
            data.add(profitAnalyse.getDailyInterestRate());
        }

        profitAnalysisJSONS.setDataAxis(dataAxis);
        profitAnalysisJSONS.setData(data);
        return profitAnalysisJSONS;
    }
}